
package br.com.positrot.controller.converter;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import br.com.positrot.controller.managedbean.MenuPrincipalMB;
import br.com.positrot.controller.util.FacesUtil;
import br.com.positrot.model.vo.SiteVO;


public class SiteConverter implements Converter {
	
	public Object getAsObject(FacesContext context, UIComponent component, String value) {

		if (value == null || value.isEmpty()){
			return new SiteVO();
		}
		
		SiteVO site = null;
		
		MenuPrincipalMB menuPrincipal = (MenuPrincipalMB) FacesUtil.getBean("#{menuPrincipalMB}");
		
		List<SiteVO> sites = menuPrincipal.getSitesCadastrados();
		
		for (SiteVO siteVO : sites) {
			if (siteVO.getDescricao().equalsIgnoreCase(value)){
				site = siteVO;
				break;
			}
		}
				
		return site;
		
	}
	
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		
		MenuPrincipalMB menuPrincipal = (MenuPrincipalMB) FacesUtil.getBean("#{menuPrincipalMB}");
		
		int indexSite = menuPrincipal.getSitesCadastrados().indexOf(value);

		if (indexSite == -1){
			return "";
		}else {
			return menuPrincipal.getSitesCadastrados().get(indexSite).getDescricao();
		}
						
	}
}
